package com.ruicar.afs.cloud.manage.costexempt.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.common.config.ContractFeginConfig;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.enums.*;
import com.ruicar.afs.cloud.manage.api.dto.BasicExpenseRecordDetailDto;
import com.ruicar.afs.cloud.manage.api.feign.info.BasicMainInfoFeign;
import com.ruicar.afs.cloud.manage.common.entity.ManageCostExempt;
import com.ruicar.afs.cloud.manage.common.entity.ManageCostExemptConfig;
import com.ruicar.afs.cloud.manage.common.entity.ManageCostExemptDetailed;
import com.ruicar.afs.cloud.manage.common.service.ManageCostExemptConfigService;
import com.ruicar.afs.cloud.manage.common.service.ManageCostExemptDetailedService;
import com.ruicar.afs.cloud.manage.common.service.ManageCostExemptService;
import com.ruicar.afs.cloud.manage.costexempt.condition.CostExemptCondition;
import com.ruicar.afs.cloud.manage.workflow.entity.WorkTaskCreatedInfo;
import com.ruicar.afs.cloud.manage.workflow.enums.NormalSubmitEnum;
import com.ruicar.afs.cloud.manage.workflow.processor.ContractWorkFlowSaveApproveInfoProcessor;
import com.ruicar.afs.cloud.manage.workflow.service.WorkTaskCreatedInfoService;
import com.ruicar.afs.cloud.manage.workflow.service.WorkflowSubmitService;
import com.ruicar.afs.cloud.manage.workflow.vo.TaskSubmitVO;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: sang jian
 * @date: 2020/8/11 18:00
 * @description:
 */
@Slf4j
@RestController
@RequestMapping("/costExemptWorkFlow")
@AllArgsConstructor
public class CostExemptWorkFlowController {

    private WorkTaskCreatedInfoService workTaskCreatedInfoService;
    private final ContractWorkFlowSaveApproveInfoProcessor saveApproveInfoProcessor;
    private final WorkflowSubmitService workflowSubmitService;
    private final ManageCostExemptDetailedService manageCostExemptDetailedService;
    private final   ManageCostExemptService manageCostExemptService;
    private ContractFeginConfig contractFeginConfig;
    private final BasicMainInfoFeign basicMainInfoFeign;
    private final ManageCostExemptConfigService manageCostExemptConfigService;


    @PostMapping("/costExemptApprove")
    @ApiOperation(value = "费用豁免审批")
    @Transactional
    public IResponse costExemptApprove(@RequestBody CostExemptCondition condition) {
        //同步数据请求头
        Map<String, String> headers = new HashMap<>();
        headers.put(AfsEnumUtil.key(ContractFeginParamEnum.BASIC_CLIENT_ID),contractFeginConfig.getBasicClientId());
        headers.put(AfsEnumUtil.key(ContractFeginParamEnum.BASIC_CLIENT_SECRET),contractFeginConfig.getBasicClientSecret());

        CaseStatusEnum caseStatusEnum = null;
        ProcessStatusEnum processStatusEnum = null;
        Long id = condition.getId();
        ManageCostExempt costExempt = manageCostExemptService.getById(id);


        if (AfsEnumUtil.key(NormalSubmitEnum.SUGGEST_CHECK_FINAL).equals(condition.getApprovalOperating())) {
            Assert.isTrue((boolean)basicMainInfoFeign.costExemptValid(condition.getContractNo(),headers).getData(),"当前合同正在扣款中,不可做费用豁免,请点击拒绝!");
            WorkTaskCreatedInfo workTaskCreatedInfo = workTaskCreatedInfoService.getOne(Wrappers.<WorkTaskCreatedInfo>query().lambda()
                    .eq(WorkTaskCreatedInfo::getBizDataId, condition.getId()).orderByDesc(WorkTaskCreatedInfo::getCreateTime), false
            );
            if (ProcessStatusEnum.approved.name().equals(workTaskCreatedInfo.getTaskMemo())) {
                condition.setEndDate(DateUtil.date());
                //是否生效
                condition.setIsEffect(YesOrNoEnum.yes);
                caseStatusEnum = CaseStatusEnum.APPROVED;
                processStatusEnum = ProcessStatusEnum.approved;


            } else if (ProcessStatusEnum.end.name().equals(workTaskCreatedInfo.getTaskMemo())) {
                condition.setEndDate(DateUtil.date());
                //是否生效
                condition.setIsEffect(YesOrNoEnum.yes);
                caseStatusEnum = CaseStatusEnum.APPROVED;
                processStatusEnum = ProcessStatusEnum.approved;
            } else {
                caseStatusEnum = CaseStatusEnum.UNDER_REVIEW;
                processStatusEnum = ProcessStatusEnum.underReview;
            }

            //审批通过,结束日期就是当前时间
            condition.setEndDate(DateUtil.date());
            condition.setStatus(processStatusEnum.toString());
            saveApproveInfoProcessor.saveApproveInfo(condition, ContractBusinessEnum.costExempt, caseStatusEnum, BusinessUrlEnum.COST_EXEMPT);

            //已通过审核,修改豁免费用详细表
            if(ProcessStatusEnum.approved.toString().equals(condition.getStatus())){
                List<ManageCostExemptDetailed> detailedList = manageCostExemptDetailedService.list(Wrappers.<ManageCostExemptDetailed>query().lambda()
                        .eq(ManageCostExemptDetailed::getExemptId, condition.getId()));
                if(detailedList.size() > 0){
                    List<BasicExpenseRecordDetailDto> basicExpenseRecordDetailList = new ArrayList<>();
                    BasicExpenseRecordDetailDto basicExpenseRecordDetailCondition2= new BasicExpenseRecordDetailDto();

                    for (ManageCostExemptDetailed detailed : detailedList){
                        //修改额度限制表中剩余额度
                        ManageCostExemptConfig oneConfig = manageCostExemptConfigService.getOne(Wrappers.<ManageCostExemptConfig>query().lambda()
                                .eq(ManageCostExemptConfig::getDeptId, SecurityUtils.getUser().getDeptId())
                                .eq(ManageCostExemptConfig::getCostType, detailed.getCostType().toString())
                                .eq(ManageCostExemptConfig::getType, CostExemptTypeEnum.total)
                        );
                        if(oneConfig != null){
                            oneConfig.getSurplusLimitAmt().subtract(detailed.getExemptionAmt());
                        }
                        //修改basic中的数据
                        BasicExpenseRecordDetailDto basicExpenseRecordDetailCondition = new BasicExpenseRecordDetailDto();
                        basicExpenseRecordDetailCondition.setId(detailed.getExpenseDetailId());
                        basicExpenseRecordDetailCondition.setContractNo(detailed.getContractNo());
                        basicExpenseRecordDetailCondition.setCostType(detailed.getCostType());
                        basicExpenseRecordDetailCondition.setExemptionAmt(detailed.getExemptionAmt());
                        basicExpenseRecordDetailList.add(basicExpenseRecordDetailCondition);
                    }
                    basicExpenseRecordDetailCondition2.setBasicExpenseRecordDetailList(basicExpenseRecordDetailList);
                    Assert.isTrue((boolean)basicMainInfoFeign.costExemptApprovel(basicExpenseRecordDetailCondition2,headers).getData(),"提交失败,请重试!");
                }
            }
        } else if (AfsEnumUtil.key(NormalSubmitEnum.SUGGEST_REJECT_FINAL).equals(condition.getApprovalOperating())) {
            condition.setEndDate(DateUtil.date());
            condition.setStatus(ProcessStatusEnum.refuse.toString());
            saveApproveInfoProcessor.saveApproveInfo(condition, ContractBusinessEnum.costExempt, CaseStatusEnum.REFUSE, BusinessUrlEnum.COST_EXEMPT);
            //修改豁免费用详细表
            //修改basic中的状态
            List<ManageCostExemptDetailed> detailedList = manageCostExemptDetailedService.list(Wrappers.<ManageCostExemptDetailed>query().lambda()
                    .eq(ManageCostExemptDetailed::getExemptId, condition.getId()));
            if(detailedList.size() > 0){
                List<Long> eIds = new ArrayList<>();
                for (ManageCostExemptDetailed detailed : detailedList){
                    eIds.add(detailed.getExpenseDetailId());
                }
                //修改basic中的数据
                BasicExpenseRecordDetailDto dto= new BasicExpenseRecordDetailDto();
                dto.setExpenseDetailIds(eIds);
                //被拒绝了,basic合同费用表改回未还清状态
                dto.setStatus("unsettle");
                Assert.isTrue((boolean)basicMainInfoFeign.changeExpenseRecordStatus(dto, headers).getData(),"操作失败,请重试!");
            }
        } else if (AfsEnumUtil.key(NormalSubmitEnum.SEND_BACK).equals(condition.getApprovalOperating())) {
            Assert.isTrue((boolean)basicMainInfoFeign.costExemptValid(condition.getContractNo(),headers).getData(),"当前合同正在扣款中,不可做费用豁免,请点击拒绝!");
            //退回不需要改结束日期
           // condition.setEndDate(DateUtil.date());
            condition.setStatus(ProcessStatusEnum.toBeRepaired.toString());
            saveApproveInfoProcessor.saveApproveInfo(condition, ContractBusinessEnum.costExempt, CaseStatusEnum.NOT_SUBMIT, BusinessUrlEnum.COST_EXEMPT);
        }

        manageCostExemptService.updateById(condition);

        String jsonString = JSONObject.toJSONString(condition);
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        TaskSubmitVO taskSubmitVO = new TaskSubmitVO();
        taskSubmitVO.setBizData(jsonObject);
        taskSubmitVO.setApprovalOperating(condition.getApprovalOperating());
        taskSubmitVO.setApprovalOpinion(condition.getApprovalOpinion());
        taskSubmitVO.setReasonType(condition.getReasonType());
        workflowSubmitService.submit(taskSubmitVO);
        return IResponse.success("操作成功");
    }
}
